package com.xuesi.demoadmin.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.xuesi.demoadmin.entity.R;
import com.xuesi.demoadmin.entity.User;
import com.xuesi.demoadmin.service.IUserService;
import com.xuesi.demoadmin.utils.Md5Utils;
import com.xuesi.demoadmin.utils.PageUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.xuesi.demoadmin.annotation.Auth;
import com.xuesi.demoadmin.annotation.Permission;
import com.github.pagehelper.PageInfo;

@RestController
@RequestMapping("/api/users")
public class UserController {
    @Autowired
    private IUserService userService;

    @Auth
    @Permission
    @PostMapping("/add")
    public R<Object> add(@Validated @RequestBody User user) {
        if (!userService.checkPhoneUnique(user)) {
            String msg = "新增用户'" + user.getName() + "'失败，手机号码已存在";
            return new R<Object>(500, msg);
        }

        Date now = new Date();
        user.setCreatedAt(now);
        user.setUpdatedAt(now);
        user.setPassword(Md5Utils.hash(user.getPassword()));

        userService.insertUser(user);
        return new R<Object>(200, "success");
    }

    @SuppressWarnings("unchecked")
    @Auth
    @Permission
    @GetMapping("/list")
    public R<Map<String, Object>> list(@RequestBody User user) {
        // 设置请求分页数据
        try {
            PageUtils.startPage();
        } catch (Exception e) {
            return null;
        }

        List<User> list = this.userService.selectUserList(user);

        Map<String, Object> result = new HashMap<>();

        result.put("count", new PageInfo(list).getTotal());
        result.put("list", list);

        return new R<Map<String, Object>>(200, "success", result);
    }
}
